import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  final _refreshController = RefreshController();
  final ScrollController _scrollController = ScrollController();

  late TabController _tabController;

  late AnimationController _animationController;
  late Animation<double> _animation;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _tabController = TabController(length: 4, vsync: this);

    _animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
    _animation = Tween(begin: 1.0, end: 0.0).animate(_animationController)
    ..addListener(() {
      setState(() {
        
      });
    });

    _scrollController.addListener(_scroll);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _refreshController.dispose();
    _scrollController.dispose();
  }

  void _scroll() {
    if (_scrollController.position.userScrollDirection == ScrollDirection.forward) {
      if (_scrollController.offset <= 0) {
        _animationController.reverse();
      }
    } else {
      _animationController.forward();
    }
  }

  AppBar _renderAppBar() {
    return AppBar(
      titleSpacing: 0.0,
      toolbarHeight: 100 - 50 * (1 - _animation.value),
      title: Container(
        width: double.infinity,
        height: 100 - 50 * (1 - _animation.value),
        color: Colors.grey,
        child: Stack(
          children: [
            const Row(
              children: [
                Text('logo'),
                Expanded(child: SizedBox()),
                Icon(Icons.notifications)
              ],
            ),

            Positioned(
              bottom: 5,
              left: 50 * (1 - _animation.value),
              child: Container(
                width: 360 - 100 * (1 - _animation.value),
                height: 40,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.blue[200],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  SliverAppBar _renderSliverAppBar() {
    return SliverAppBar(
      pinned: true,
      titleSpacing: 0.0,
      toolbarHeight: 100 - 50 * (1 - _animation.value),
      title: Container(
        width: double.infinity,
        height: 100 - 50 * (1 - _animation.value),
        color: Colors.grey,
        child: Stack(
          children: [
            const Row(
              children: [
                Text('logo'),
                Expanded(child: SizedBox()),
                Icon(Icons.notifications)
              ],
            ),

            Positioned(
              bottom: 5,
              left: 50 * (1 - _animation.value),
              child: Container(
                width: 360 - 100 * (1 - _animation.value),
                height: 40,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.blue[200],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _customScrollView() {
    return CustomScrollView(
      controller: _scrollController,
      slivers: [
        _renderSliverAppBar(),

        SliverToBoxAdapter(
          child: Container(
            width: double.infinity,
            height: 200,
            color: Colors.grey[300],
          ),
        ),

        SliverPersistentHeader(
          delegate: _SliverAppBarDelegate(TabBar(
            controller: _tabController,
            labelColor: Colors.black87,
            unselectedLabelColor: Colors.grey,
            tabs: const [
              Tab(text: "标签一"),
              Tab(text: "标签二"),
              Tab(text: "标签三"),
              Tab(text: "标签四"),
            ],
          )),
          pinned: true,
        ),

        SliverFillRemaining(
          child: TabBarView(
            controller: _tabController,
            children: const [
              Center(child: Text("第一个标签的内容")),
              Center(child: Text("第二个标签的内容")),
              Center(child: Text("第三个标签的内容")),
              Center(child: Text("第四个标签的内容"))
            ],
          ),
        )
      ],
    );
  }

  Widget _nestedScrollView() {
    return NestedScrollView(
      controller: _scrollController,
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          SliverToBoxAdapter(
            child: Container(
              width: double.infinity,
              height: 200,
              color: Colors.grey[300],
            ),
          ),
          SliverPersistentHeader(
            delegate: _SliverAppBarDelegate(const TabBar(
              labelColor: Colors.black87,
              unselectedLabelColor: Colors.grey,
              tabs: [
                Tab(text: "标签一"),
                Tab(text: "标签二"),
                Tab(text: "标签三"),
                Tab(text: "标签四"),
              ],
            )),
            pinned: true,
          ),
        ];
      },
      body: const TabBarView(
        children: [
          Center(child: Text("第一个标签的内容")),
          Center(child: Text("第二个标签的内容")),
          Center(child: Text("第三个标签的内容")),
          Center(child: Text("第四个标签的内容"))
        ],
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        // appBar: _renderAppBar(),
        body: SmartRefresher(
          controller: _refreshController,
          enablePullDown: true,
          enablePullUp: true,
          // header: const ClassicHeader(),
          header: const WaterDropHeader(),
          footer: const ClassicFooter(),
          onRefresh: () async {
            await Future.delayed(const Duration(seconds: 2));
            // 下拉刷新
            _refreshController.refreshCompleted();
          },
          onLoading: () {
            // 加载更多
            _refreshController.loadComplete();
          },
          child: _customScrollView(),
        )
      )
      
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate(this._tabBar);

  final TabBar _tabBar;

  @override
  double get minExtent => _tabBar.preferredSize.height;
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return false;
  }
}